<template>
  <div class="calculate-score" v-loading="loading" :style="{height: height}" ref="standardListTop">
    <div class="base-terms-content">
      <div class="location-type-all">
        <el-button type="primary" @click="allExpand(false)" style="margin-left: 30px;">
          <span v-show="inspectionData.terms.length > collapseValue.length">全部展开 <i class="el-icon-arrow-right" /></span>
          <span v-show="inspectionData.terms.length <= collapseValue.length">全部折叠 <i class="el-icon-arrow-down" /></span>
        </el-button>
      </div>
      <el-collapse v-model="collapseValue" class="calculate-score-collapse">
        <el-collapse-item v-for="(terms, index) in inspectionData.terms" :key="'terms' + index" class="base-terms-item" :name="'termsCarousel' + index">
          <div slot="title" class="check-type" v-if="terms.tableId != 'sjdf' && terms.tableId != 'jzsjdf' && terms.tableId != 'tjcbspkf' && terms.tableId != 'jzcbspkf'">
            <!--{{ terms.levelType == 'base' ? index : index - inspectionData.count.base - 1 }}、{{ terms.tableName }}-->
            <div v-if="moduleOption(terms, index)" class="gldz-module" :class="{'gldz-module-danger': judgeDanger(terms)}">
              <span>{{ terms.parentLevelCode | parentLevelCode(parentNodeList) }}</span>
              <span style="margin-left: 30px;">【{{ inspectionData[terms.parentLevelCode] }} 分】</span>
              <span class="all-no-check" v-if="groupKeys[terms.parentLevelCode]">
                <el-checkbox v-model="groupKeys[terms.parentLevelCode].result" :true-label="-1" :false-label="0" @change="noCheckModule($event,terms.parentLevelCode)">甩项</el-checkbox>
              </span>
            </div>
            <div>
              <span>{{ index + 1 }}、{{ terms.tableName }}</span>
              <div v-if="terms.codeAncestorNameList" style="display: inline-block;">
                <el-tag class="location-type" v-for="level in terms.codeAncestorNameList" :key="level.code">{{ level.name }}</el-tag>
              </div>
            </div>
          </div>
          <div slot="title" v-else class="check-type" style="min-height:46px;">
            <div class="gldz-module">
              <span>{{ terms.tableName }}</span>
              <span style="margin-left: 30px;">【{{ terms.score }} 分】</span>
            </div>
            <span>{{ index + 1 }}、{{ terms.tableName }}</span>
          </div>
          <div v-if="terms.tableId == 'sjdf' || terms.tableId == 'jzsjdf'" class="point-content">
            <span class="design-label">设计得分</span>
            <el-input-number v-model="terms.score" @change="handleDesignChange(terms)" placeholder="请输入设计得分" />
            <div class="value-grade" style="margin-left: 70px;">*取值范围：0 ~ 50</div>
            <div style="margin: 10px 0 0 70px;">
              <el-input
                type="textarea"
                show-word-limit
                :maxlength="1000"
                :disabled="terms.result === -1"
                :autosize="{ minRows: 2, maxRows: 4}"
                placeholder="请输入备注"
                v-model="terms.remark"
                @change="remarkChange(terms)"
              />
            </div>
          </div>
          <div v-else-if="terms.tableId == 'tjcbspkf' || terms.tableId == 'jzcbspkf'" class="point-content">
            <span class="design-label">成本适配扣分</span>
            <el-input-number v-model="terms.score" @change="handleFitChange(terms)" placeholder="请输入成本适配扣分" />
            <div class="value-grade">*取值范围：-100 ~ 0</div>
            <div style="margin: 10px 0 0 100px;">
              <el-input
                type="textarea"
                show-word-limit
                :maxlength="1000"
                :disabled="terms.result === -1"
                :autosize="{ minRows: 2, maxRows: 4}"
                placeholder="请输入备注"
                @change="remarkChange(terms)"
                v-model="terms.remark"
              />
            </div>
          </div>
          <div v-else>
            <div v-for="(point, indexP) in terms.standardList" :key="'point' + indexP" class="point-content" :ref="point.randomString">
              <!--test data 测试参数-->
              <div class="point-descr">
                <div :class="{'danger': point.itemLevel == '2' || point.itemLevel == '3'}" style="margin-right: 20px;">
                  <span v-if="point.itemLevel==3">*</span>{{ indexP + 1 }}、{{ point.standardContent }}
                  <el-tooltip effect="dark" placement="top-start">
                    <div slot="content" style="max-width: 400px;line-height: 20px;">评判规则：{{ point.ruleContent }}</div>
                    <i class="el-icon-question rule-content" />
                  </el-tooltip>
                  <el-tag v-if="point.ruleType==5" type="danger">检测点要求：{{ point.mixCheck }}个</el-tag>
                </div>
                <!--甩项-->
                <div class="no-check">
                  <el-checkbox v-model="point.result" :true-label="-1" :false-label="10" @change="noCheck(point)" @click.native="noCheckNative(point)">甩项</el-checkbox>
                </div>
              </div>
              <!--条件条款-->
              <div v-if="point.conditionOptions" class="operater-condition">
                <el-radio-group v-model="point.itemSel" :disabled="point.result === -1" @input="conditionChange($event,point)">
                  <el-radio :label="condition.name" v-for="(condition, cindex) in point.conditionOptions" :key="'condition' + cindex">{{ condition.name }}</el-radio>
                </el-radio-group>
              </div>
              <div class="data-row">
                <!--显示符合还是不符合-->
                <div v-if="point.ruleType==3" class="operater-first">
                  <el-radio-group v-model="point.result" :disabled="point.result === -1" @input="overallEvaluation">
                    <el-radio :label="accord.value" v-for="(accord, aindex) in accordOptions" :key="'accord' + aindex">{{ accord.name }}</el-radio>
                  </el-radio-group>
                </div>
                <!-- 违反扣分： 实际检查 与 合格数量-->
                <div v-else-if="point.ruleType==5" class="operater-first">
                  <el-input :disabled="point.result === -1" placeholder="请输入" v-model.number="point.checkTotal" class="input-width" @change="badTotalChange(point)">
                    <template slot="prepend">实际检查:</template>
                    <template slot="append">{{ point.ruleUnit || '处' }}</template>
                  </el-input>
                  <el-input :disabled="point.result === -1" placeholder="请输入" v-model.number="point.goodTotal" class="input-width" style="margin-top: 10px;" @change="badTotalChange(point)">
                    <template slot="prepend">合格数量:</template>
                    <template slot="append">{{ point.ruleUnit || '处' }}</template>
                  </el-input>
                </div>
                <!--ruleType 1,2,4,6,7,8-->
                <div v-else class="operater-first">
                  <el-input :disabled="point.result === -1 || !point.ruleType" placeholder="请输入" v-model.number="point.badTotal" class="input-width" @change="badTotalChange(point)">
                    <template slot="prepend">违反:</template>
                    <template slot="append">{{ point.ruleUnit || '处' }}</template>
                  </el-input>
                  <div v-if="!point.ruleType" class="remain-desc">*请先配置抽检规则</div>
                </div>
                <!--根据阈值，判定是否违反标准-->
                <el-tag v-if="point.isViolateStandard" type="danger" size="large" class="violate-standard">违反标准</el-tag>
              </div>
              <div class="vos-area-list">
                <template v-if="point.areaList">
                  <div class="item" v-for="(areaItem, areaIndex) in point.areaList" :key="'area-item' + areaIndex" :title="areaItem.shortName">
                    <i v-if="!terms.checkboxStatus && point.result !== -1" class="el-icon-circle-close btn-del" @click="removeArea(point.areaList, areaItem, areaIndex)" />
                    <el-image class="img g-img-placeholder" :src="areaItem.url" fit="cover" :initial-index="areaIndex" :preview-src-list="point.areaList.map(i => i.url)" />
                    <!--<div class="area-name ellipsis2" v-if="point.result === -1">{{ areaItem.shortName || '暂无选择位置' }}</div>
                    <div class="area-name ellipsis2" v-else>
                      <el-checkbox class="area-checkbox" v-model="areaItem.checked" :class="{ checked: areaItem.checked }" @change="toggleCheckboxForOtherItems(index)" />
                      <span @click="selectStandardArea(point, areaItem, index, indexP, areaIndex)" :class="{ pointer: !isMultiAreas }">{{ areaItem.shortName || '选择位置' }}</span>
                    </div>-->
                  </div>
                </template>
                <div class="item" v-if="canSaveItems && !terms.checkboxStatus && point.result !== -1">
                  <div class="area-select-img el-upload--picture-card" @click="openSelectFileList(index, indexP)">
                    <i class="el-icon-plus" />
                  </div>
                </div>
              </div>
              <div style="margin-top: 10px;">
                <el-input
                  type="textarea"
                  show-word-limit
                  :maxlength="1000"
                  :disabled="point.result === -1"
                  :autosize="{ minRows: 2, maxRows: 4}"
                  placeholder="请输入备注"
                  v-model="point.remark"
                />
              </div>
            </div>
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>
    <div v-if="inspectionData.terms.length == 0" class="custom-is-empty">
      <el-empty description="暂无数据。" />
    </div>
    <!--问题区域选取-->
    <SelectArea ref="SelectArea" @ok="onSelectArea" />
    <SelectFileList ref="SelectFileList" multiple @ok="onSelectFileList" />
  </div>
</template>

<script>
import store from '@/store'
import auth from '@/plugins/auth'
import { generateTaskRectifyTmpId, assignAreaPosition } from '@/utils/cq'
import SelectArea from './selectArea'
import SelectFileList from './SelectFileList'
import evaluation from '../evaluation'
import constant from '../constant'
export default {
  name: 'CalculateScore',
  components: { SelectArea, SelectFileList },
  filters: {
    locationType(val) {
      let name = ''
      if (val === 'hn') {
        name = '户内'
      } else if (val === 'gq') {
        name = '公区'
      } else if (val === 'wlm') {
        name = '外立面'
      }
      return name
    },
    parentLevelCode(code, parentNodeList) {
      let name = ''
      for (let i = 0; i < parentNodeList.length; i++) {
        if (code === parentNodeList[i].courseCode) {
          name = parentNodeList[i].couseName
        }
      }
      /* switch (code) {
        case 'mphnjfyzyb':
          name = '毛坯户内交付业主样板'
          break
        case 'gqjfyzyb':
          name = '公区交付业主样板'
          break
        case 'wlmjfyzyb':
          name = '外立面交付业主样板'
          break
        case 'tjcpssx':
          name = '土建产品舒适性'
          break
        case 'jzgczldf':
          name = '精装工程质量得分'
          break
        case 'jzcpssx':
          name = '精装产品舒适性'
          break
        default:
          break
      }*/
      return name
    }
  },
  props: {
    height: {
      type: String,
      default: () => '75vh'
    },
    gldzLevel: {
      type: String,
      default: () => '2' // 2 土建楼层会验；3 精装交付样板会验
    },
    checkRecordRow: { // 当前 抽检过程 数据
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      loading: false,
      inspectionData: {
        terms: [],
        result: 10, // 10 合格， 11 不合格
        score: ''
      },
      detailScore: { // 观感、空鼓开裂 得分详细
        indoor: 0,
        publicArea: 0,
        outsideWall: 0
      },
      isConstruction: true, // 土建过程 或 false 精装
      // 统一文件上传接口
      uploadUrl: process.env.VUE_APP_BASE_API + '/file/multiUpload',
      accordOptions: [
        {
          name: '符合',
          value: 10
        },
        {
          name: '不符合',
          value: 11
        }
      ],
      locationType: {
        group: [],
        checkAll: false
      },
      // 当前条款内选中的图片，用于选完位置后(批量)赋值。list: { stdIndex: number, areaIndex: number, area: object }[]
      currTermAreas: { termIndex: 0, unitType: '', list: [] },
      // 当前标准位置，用于选完图片后赋值
      currStandard: { termIndex: 0, stdIndex: 0 },
      // 批量选位置模式
      isMultiAreas: false,
      groupKeys: {
        mphnjfyzyb: {
          first: -1, // 第一项出现下标
          result: 0, // result -1 为甩项
          gldzLevel: '2' // 父级 课程courseCode
        },
        gqjfyzyb: {
          first: -1,
          result: 0,
          gldzLevel: '2'
        },
        wlmjfyzyb: {
          first: -1,
          result: 0,
          gldzLevel: '2'
        },
        tjcpssx: {
          first: -1,
          result: 0,
          gldzLevel: '2'
        },
        tjcnyzx: {
          first: -1,
          result: 0,
          gldzLevel: '2'
        },
        tjjsx: {
          first: -1,
          result: 0,
          gldzLevel: '2'
        },
        tjtzyzx: {
          first: -1,
          result: 0,
          gldzLevel: '2'
        },
        tjwzx: {
          first: -1,
          result: 0,
          gldzLevel: '2'
        },
        jzgczldf: {
          first: -1,
          result: 0,
          gldzLevel: '3'
        },
        jzcpssx: {
          first: -1,
          result: 0,
          gldzLevel: '3'
        },
        jzcnyzx: {
          first: -1,
          result: 0,
          gldzLevel: '3'
        },
        jzjsx: {
          first: -1,
          result: 0,
          gldzLevel: '3'
        },
        jztzyzx: {
          first: -1,
          result: 0,
          gldzLevel: '3'
        },
        jzwzx: {
          first: -1,
          result: 0,
          gldzLevel: '3'
        }
      },
      collapseValue: [],
      parentNodeList: []
    }
  },
  computed: {
    canSaveItems() {
      // 有权保存
      const userFid = store.getters.user?.fid
      const roles = store.getters.roles || []
      const { processType, principalId } = this.checkRecordRow || {}

      // 用户含抽检角色时，需为本项目指定的抽检人员才有权限
      if (roles.includes('GCCJRY')) return principalId === userFid

      // 不含抽检角色，有保存权限时，需为有授权的项目（项目列表即展示有授权的，这里不需判断）
      return auth.hasPermi(`cq:${processType}:saveItems`)
    }
  },
  created() { // 初始化
    const path = this.$route.path
    this.isConstruction = path.includes('ConstructionCourse')
  },
  methods: {
    allExpand(expand) {
      if (expand) {
        this.collapseValue = []
        for (let i = 0; i < this.inspectionData.terms.length; i++) {
          this.collapseValue.push('termsCarousel' + i)
        }
      } else {
        if (this.collapseValue.length >= this.inspectionData.terms.length) {
          this.collapseValue = []
        } else {
          for (let i = 0; i < this.inspectionData.terms.length; i++) {
            this.collapseValue.push('termsCarousel' + i)
          }
        }
      }
    },
    // 在甩项 result值 改变前调用 保存到 originalResult
    noCheckNative(point) {
      if (point.result !== -1) {
        point.originalResult = point.result
      }
    },
    noCheck(point) { // 无法检查 甩项
      if (point.result !== -1) {
        point.result = point.originalResult
      }
      this.judgeAllNoCheck(this.inspectionData.terms)
      this.overallEvaluation()
    },
    // 甩项 模块变化
    noCheckModule(val, code) {
      console.log(val, code)
      const terms = this.inspectionData.terms
      for (let i = 0; i < terms.length; i++) {
        for (let j = 0; j < terms[i].standardList.length; j++) {
          let codeAncestors = []
          try {
            codeAncestors = terms[i].standardList[j].codeAncestors.split(',')
          } catch (e) {
            console.log(e)
          }
          let parentLevelCode = ''
          if (codeAncestors.length > 0) {
            if (codeAncestors[codeAncestors.length - 1] === 'jzggzl') { // jzggzl 属于 jzgczldf 子集
              parentLevelCode = 'jzgczldf'
            } else {
              parentLevelCode = codeAncestors[codeAncestors.length - 1]
            }
            if (parentLevelCode === code) {
              if (val) {
                if (terms[i].standardList[j].result && terms[i].standardList[j].result !== -1) {
                  terms[i].standardList[j].originalResult = terms[i].standardList[j].result // 甩项前 结果备份
                }
                terms[i].standardList[j].result = -1
              } else {
                if (terms[i].standardList[j].originalResult === -1) {
                  terms[i].standardList[j].result = 0
                } else {
                  terms[i].standardList[j].result = terms[i].standardList[j].originalResult
                }
              }
            }
          }
        }
      }
      this.overallEvaluation()
    },
    judgeDanger(terms) {
      let status = false
      // 倒扣分项 code
      const reduceCodes = constant.gldz.ybyspj.reduceScoreCodes
      if (reduceCodes.some(code => code === terms.parentLevelCode)) {
        status = parseFloat(this.inspectionData[terms.parentLevelCode]) < -20
      } else {
        status = parseFloat(this.inspectionData[terms.parentLevelCode]) < 80
      }
      return status
    },

    moduleOption(terms, index) {
      const keys = Object.keys(this.groupKeys)
      if (keys.some(key => key === terms.parentLevelCode)) {
        if (this.groupKeys[terms.parentLevelCode].first === -1) {
          this.groupKeys[terms.parentLevelCode].first = index
        }
        if (this.groupKeys[terms.parentLevelCode].first === index) {
          return true
        } else {
          return false
        }
      }
    },
    remarkChange(obj) {
      obj.standardList[0].remark = obj.remark
    },
    // 设计分改变
    handleDesignChange(obj) {
      if (!/^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/.test(obj.score)) {
        if (Number(obj.score)) {
          obj.score = parseFloat(obj.score.toFixed(2))
        } else {
          obj.score = null
          return
        }
      }
      if (obj.score < 0 || obj.score > 50) {
        this.$message.warning('得分项请输入大于0数字。')
        this.$message({ message: '设计得分项取值范围 0 ~ 50数字。', type: 'warning', duration: 5000 })
        obj.score = null
        return
      }
      const terms = this.inspectionData.terms
      for (let i = 0; i < terms.length; i++) {
        if (terms[i].tableId.includes('sjdf')) {
          terms[i].standardList[0].score = terms[i].score || 0
          terms[i].standardList[0].result = terms[i].score < 40 ? 11 : 10
        }
      }
      this.overallEvaluation()
    },
    // 成本适配扣分
    handleFitChange(obj) {
      if (!/^((\-[1-9]{1}\d*)(\.\d{1,2})?|(0{1}))$/.test(obj.score)) {
        if (Number(obj.score)) {
          if (obj.score > 0) {
            this.$message({ message: '扣分项取值范围 -100 ~ 0数字。', type: 'warning', duration: 5000 })
            obj.score = null
            return
          } else {
            obj.score = parseFloat(obj.score.toFixed(2))
          }
        } else {
          obj.score = null
          return
        }
      }
      if (obj.score < -100) {
        this.$message({ message: '扣分项请输入范围 -100 ~ 0数字。', type: 'warning', duration: 5000 })
        obj.score = null
        return
      }
      const terms = this.inspectionData.terms
      for (let i = 0; i < terms.length; i++) {
        if (terms[i].tableId.includes('cbspkf')) {
          terms[i].standardList[0].score = terms[i].score || 0
          terms[i].standardList[0].result = terms[i].score < -20 ? 11 : 10
        }
      }
      this.overallEvaluation()
    },
    // 条件条款 切换
    conditionChange(name, point) {
      const conditionOptions = point.conditionOptions
      for (let j = 0; j < conditionOptions.length; j++) {
        if (conditionOptions[j].name === name) {
          point.ruleJson = conditionOptions[j].ruleJson
          point.ruleType = conditionOptions[j].ruleType
          point.ruleUnit = conditionOptions[j].ruleUnit
        }
      }
      this.badTotalChange(point)
    },
    /*
    *  初始化
    *  父组件调用
    * */
    init(inspectionData, parentNodeList) {
      this.collapseValue = inspectionData.collapseValue || []
      this.parentNodeList = parentNodeList
      const sortIndex = ['tjlchy', 'mphnjfyzyb', 'gqjfyzyb', 'wlmjfyzyb', 'tjwzx', 'tjjsx', 'tjtzyzx', 'tjcpssx', 'tjcnyzx',
        'jzsjdf', 'jzjfybys', 'jzgczldf', 'jzwzx', 'jzjsx', 'jztzyzx', 'jzcpssx', 'jzcnyzx'] // 'tjlchy', 'jzjfybys' 对应设计得分 排序位置
      for (let i = 0; i < inspectionData.terms.length; i++) {
        const codes = ['sjdf', 'jzsjdf', 'tjcbspkf', 'jzcbspkf'] // 直接输入 相关code
        if (codes.some(code => code === inspectionData.terms[i].tableId)) {
          inspectionData.terms[i].score = inspectionData.terms[i].standardList[0].score
          inspectionData.terms[i].remark = inspectionData.terms[i].standardList[0].remark
        }
        if (inspectionData.terms[i].codeAncestors) {
          let codeAncestors = []
          try {
            codeAncestors = inspectionData.terms[i].codeAncestors.split(',')
          } catch (e) {
            console.log(e)
          }
          if (codeAncestors.length > 0) {
            if (codeAncestors[codeAncestors.length - 1] === 'jzggzl') { // jzggzl 属于 jzgczldf 子集
              inspectionData.terms[i].parentLevelCode = 'jzgczldf'
            } else {
              inspectionData.terms[i].parentLevelCode = codeAncestors[codeAncestors.length - 1]
            }
            inspectionData.terms[i].sort = sortIndex.findIndex(code => code === inspectionData.terms[i].parentLevelCode) + 1
          }
          const codeAncestorNameList = []
          if (codeAncestors instanceof Array) {
            for (let j = 0; j < codeAncestors.length; j++) {
              const levelObj = {
                code: codeAncestors[j],
                name: ''
              }
              for (let z = 0; z < parentNodeList.length; z++) {
                if (codeAncestors[j] === parentNodeList[z].courseCode) {
                  levelObj.name = parentNodeList[z].couseName
                }
              }
              /* switch (codeAncestors[j]) {
                case 'tjgczldf':
                  levelObj.name = '土建工程质量得分'
                  break
                case 'mphnjfyzyb':
                  levelObj.name = '毛坯户内交付业主样板'
                  break
                case 'gqjfyzyb':
                  levelObj.name = '公区交付业主样板'
                  break
                case 'wlmjfyzyb':
                  levelObj.name = '外立面交付业主样板'
                  break
                case 'tjcpssx':
                  levelObj.name = '产品舒适性'
                  break
                case 'jzgczldf':
                  levelObj.name = '精装工程质量得分'
                  break
                case 'jzcpssx':
                  levelObj.name = '精装产品舒适性'
                  break
                default:
                  break
              }*/
              if (levelObj.name) {
                codeAncestorNameList.push(levelObj)
              }
            }
          }
          inspectionData.terms[i].codeAncestorNameList = codeAncestorNameList
        }
      }
      inspectionData.terms.sort((obj1, obj2) => obj1.sort - obj2.sort)
      // 是否全部选择回显
      const terms = inspectionData.terms
      this.judgeAllNoCheck(terms)
      this.inspectionData = inspectionData
      this.overallEvaluation()

      this.currTermAreas = { termIndex: 0, unitType: '', list: [] }
      this.currStandard = { termIndex: 0, stdIndex: 0 }
      this.isMultiAreas = false
    },
    judgeAllNoCheck(terms) { // 回显子项 是否全部甩项
      for (const key in this.groupKeys) {
        let keyResult = -1
        for (let i = 0; i < terms.length; i++) {
          for (let j = 0; j < terms[i].standardList.length; j++) {
            let codeAncestors = []
            try {
              codeAncestors = terms[i].standardList[j].codeAncestors.split(',')
            } catch (e) {
              console.log(e)
            }
            let parentLevelCode = ''
            if (codeAncestors.length > 0) {
              if (codeAncestors[codeAncestors.length - 1] === 'jzggzl') { // jzggzl 属于 jzgczldf 子集
                parentLevelCode = 'jzgczldf'
              } else {
                parentLevelCode = codeAncestors[codeAncestors.length - 1]
              }
              if (parentLevelCode === key && terms[i].standardList[j].result !== -1) {
                keyResult = 0
              }
            }
          }
        }
        this.groupKeys[key].result = keyResult
      }
    },
    validateNoCheck () { // 判断 子项是否全部甩项
      const currentGroupKeys = {}
      const parentCodes = this.parentNodeList.map(node => node.courseCode)
      for (const key in this.groupKeys) {
        if (parentCodes.some(code => code === key)) {
          currentGroupKeys[key] = this.groupKeys[key]
        }
      }
      let noCheckAll = false
      //  毛坯、户内、外立面 可以全甩
      const noCheckKey = ['mphnjfyzyb', 'gqjfyzyb', 'wlmjfyzyb'] // 允许全甩key数组
      for (const key in currentGroupKeys) {
        if (currentGroupKeys[key].result === -1 && !noCheckKey.includes(key)) {
          noCheckAll = true
        }
      }
      return noCheckAll
    },
    /*
    * 校验提交数据
    * 父组件调用
    * */
    validateData() {
      let validate = true
      for (let i = 0; i < this.inspectionData.terms.length; i++) { // 判断所有标准 是否 检查
        for (let j = 0; j < this.inspectionData.terms[i].standardList.length; j++) {
          if (this.inspectionData.terms[i].standardList[j].result !== -1 && this.inspectionData.terms[i].standardList[j].ruleType) { // 无法检查
            const ref = this.inspectionData.terms[i].standardList[j].randomString
            if (this.inspectionData.terms[i].standardList[j].ruleType === 3) { // 符合条款
              if (![-1, 10, 11].includes(this.inspectionData.terms[i].standardList[j].result)) {
                this.controlScroll(ref)
                validate = false
                return
              }
            } else if (this.inspectionData.terms[i].standardList[j].ruleType === 5) { // 违反扣分
              if (!this.inspectionData.terms[i].standardList[j].checkTotal && this.inspectionData.terms[i].standardList[j].checkTotal !== 0 ||
                !this.inspectionData.terms[i].standardList[j].goodTotal && this.inspectionData.terms[i].standardList[j].goodTotal !== 0) {
                this.controlScroll(ref)
                validate = false
                return
              }
            } else {
              if (!this.inspectionData.terms[i].standardList[j].badTotal && this.inspectionData.terms[i].standardList[j].badTotal !== 0) {
                this.controlScroll(ref)
                validate = false
                return
              }
            }
          }
        }
      }

      // 判断同个工序是否选择了相同的图片和位置
      const termList = this.inspectionData.terms
      for (const term of termList) {
        for (const std of term.standardList) {
          const keyMap = {}
          const unitType = std.unitType || 1
          for (const area of std.areaList) {
            // 生成位置id
            const tmpId = generateTaskRectifyTmpId(unitType, area)
            if (!tmpId) continue
            const key = `${area.fileId}_${tmpId}`
            if (keyMap[key]) return void this.controlScroll(std.randomString, '同一验收标准请勿选择相同的图片和位置')
            keyMap[key] = 1
          }
        }
      }

      return validate
    },
    /*
    *  滚动到指定位置
    * */
    controlScroll(ref) {
      this.$message({
        message: '存在未填写标准项，若无异常可填写 0 或 选符合。',
        type: 'warning',
        duration: 5000
      })
      this.allExpand(true)
      setTimeout(() => {
        const scrollTop = this.$refs[ref][0].offsetTop - this.$refs.standardListTop.offsetHeight / 2 + 100
        this.$refs.standardListTop.scrollTop = scrollTop
      })
    },
    /*
    *  数量改变
    * */
    badTotalChange(data) {
      // 数据验证
      if (data.ruleType === 5) {
        if (data.checkTotal && !Number(data.checkTotal)) {
          this.$message.error('数量请输入数字！')
          data.checkTotal = null
          return
        }
        if (data.goodTotal && !Number(data.goodTotal)) {
          this.$message.error('数量请输入数字！')
          data.goodTotal = null
          return
        }
        if (data.goodTotal < 0 || data.goodTotal > 999 || data.checkTotal < 0 || data.checkTotal > 999) {
          this.$message.error('请输入在 0 ~ 999范围内数量！')
          data.goodTotal = null
          data.checkTotal = null
          return
        }
        // if (data.checkTotal < data.mixCheck) {
        //   this.$message.error('实际检查数量不能小于检查点！')
        //   data.checkTotal = null
        //   return
        // }
        if ((data.checkTotal || data.goodTotal) && Number(data.checkTotal) < Number(data.goodTotal)) {
          this.$message.error('合格数量不能大于实际检查！')
          data.goodTotal = null
          return
        }
        if (data.checkTotal < 1 && data.checkTotal > 0 || data.goodTotal < 1 && data.goodTotal > 0) {
          data.checkTotal = parseInt(data.checkTotal)
          data.goodTotal = parseInt(data.goodTotal)
        }
      } else {
        if (data.badTotal && !Number(data.badTotal)) {
          this.$message.error('数量请输入数字！')
          data.badTotal = null
          return
        }
        if (data.badTotal < 0 || data.badTotal > 999) {
          this.$message.error('请输入在 0 ~ 999范围内数量！')
          data.badTotal = null
          return
        }
        if (data.badTotal < 1 && data.badTotal > 0) {
          data.badTotal = parseInt(data.badTotal)
        }
      }
      this.setStandardResustAndScore(data)
      this.overallEvaluation()
    },
    /*
    *  设置 标准验收结果与得分
    * */
    setStandardResustAndScore(data) {
      let ruleJson = []
      try {
        ruleJson = JSON.parse(data.ruleJson)
      } catch (e) {
        console.log(e)
      }
      console.log(data.badTotal, ruleJson)
      if (ruleJson && ruleJson instanceof Array && ruleJson.length > 0) {
        if (data.ruleType === 5) { // 合格计分（违反扣分） goodTotal 与 checkTotal
          evaluation.qualifiedScore(data, ruleJson)
        } else if (data.ruleType === 6) { // 阈值扣分 （阈值范围，扣分）
          evaluation.rangeReduceScore(data, ruleJson)
        } else if (data.ruleType === 7) { // 重复扣分 （（badTotal - min) * score），扣分）
          evaluation.repetiteReduceScore(data, ruleJson)
        } else if (data.ruleType === 8) { // 直接扣分 （超过阈值 扣相同分）
          evaluation.directReduceScore(data, ruleJson)
        }
      }
    },
    /*
    *  整体评估
    * */
    overallEvaluation() {
      const rdcScore = this.checkRecordRow
      const projectId = rdcScore.projectId
      const terms = this.inspectionData.terms
      const obj = evaluation.calculateGldzScore(terms, { gldzLevel: this.gldzLevel }, this.groupKeys)
      // this.inspectionData.score = obj.score
      // this.inspectionData.result = obj.result
      Object.assign(this.inspectionData, obj)

      // 设置父节点得分
      this.setParentNode()

      const saveAreas = []
      const deleteAreas = []
      const scoreType = 'gldz'
      this.inspectionData.terms.map(term => {
        term.standardList.map(std => {
          const areas = []
          std.areaList.map(area => {
            const { itemFileId, rectifyId, standardType, fileId, taskFileId, shortName } = area
            // 从历史记录里选的
            if (rectifyId && standardType === scoreType) return areas.push({ rectifyId, fileId, taskFileId, shortName })

            // 移除 rectifyId (不表示从历史选，不应含此参数)
            const area2 = JSON.parse(JSON.stringify(area))
            delete area2.rectifyId

            const unitType = std.unitType || 1
            const item = { projectId, itemFileId, fileId, taskFileId, unitType }
            assignAreaPosition(unitType, item, area2)
            if (item.drawArea && typeof item.drawArea === 'object') {
              try {
                item.drawArea = JSON.stringify(item.drawArea)
              } catch (error) {
                console.log(error)
              }
            }
            areas.push(item)
          })

          // 判断删除的位置
          const list2 = std.areaListBackUp || []
          if (list2.length) {
            const itemFileIds = areas.map(i => i.itemFileId).filter(i => i)
            list2.map(i => {
              if (itemFileIds.includes(i.itemFileId)) return
              deleteAreas.push(i.itemFileId)
            })
          }

          if (!areas.length) return
          const item = { standardId: std.standardId, areas }
          if (std.mrqId) item.mrqId = std.mrqId
          saveAreas.push(item)
        })
      })
      this.inspectionData.saveAreas = saveAreas
      this.inspectionData.deleteAreas = deleteAreas
      this.inspectionData.parentNodeList = this.parentNodeList
      this.inspectionData.collapseValue = this.collapseValue
      // 细项得分
      /*  this.detailScore.indoor = obj.indoor
      this.detailScore.publicArea = obj.publicArea*/
      this.$emit('getScoreData', this.inspectionData)
    },
    setParentNode () {
      const keys = {mphnjfyzyb: 0, gqjfyzyb: 0, wlmjfyzyb: 0}
      for (let i = 0; i < this.parentNodeList.length; i++) {
        if (this.inspectionData[this.parentNodeList[i].courseCode] || this.inspectionData[this.parentNodeList[i].courseCode] === 0) {
          this.parentNodeList[i].score = this.inspectionData[this.parentNodeList[i].courseCode]
          if (this.parentNodeList[i].score < 80) {
            this.parentNodeList[i].result = 11
          } else {
            this.parentNodeList[i].result = 10
          }
          if (Object.keys(keys).some(key => key === this.parentNodeList[i].courseCode)) {
            keys[this.parentNodeList[i].courseCode] = this.parentNodeList[i].score
          }
        }
      }
      for (let i = 0; i < this.parentNodeList.length; i++) {
        if (this.parentNodeList[i].courseCode === 'tjgczldf') { // 土建工程质量得分
          let result = 10
          for (const key in keys) {
            if (keys[key] < 80) {
              result = 11
            }
          }
          this.parentNodeList[i].result = result
        }
      }
    },
    async removeArea(list, item, index) {
      const res1 = await this.$confirm('确认移除本项?', '警告', { type: 'warning' }).catch(() => false)
      if (res1 !== 'confirm') return
      list.splice(index, 1)
      this.overallEvaluation()
    },
    // 当前条款内是否有选中
    isCheckedInTerm(termIndex) {
      const terms = this.inspectionData.terms
      const stdList = terms[termIndex].standardList
      for (const std of stdList) {
        for (const area of std.areaList) {
          if (area.checked) return true
        }
      }
      return false
    },
    // 禁用/解除其他检查项的复选框
    toggleCheckboxForOtherItems(termIndex) {
      const terms = this.inspectionData.terms
      const checked = this.isCheckedInTerm(termIndex)
      this.isMultiAreas = checked
      this.$emit('setIsMultiAreas', checked)
      this.currTermAreas.termIndex = termIndex
      const status = checked ? 'disabled' : ''
      const currStatus = checked ? 'show' : ''
      terms.map((term, index) => {
        term.checkboxStatus = index === termIndex ? currStatus : status
      })
    },
    resetAllCheckbox() {
      const terms = this.inspectionData.terms
      terms.map(term => {
        term.checkboxStatus = ''
        term.standardList.map(std => std.areaList.map(area => (area.checked = false)))
      })
      this.isMultiAreas = false
      this.$emit('setIsMultiAreas', false)
    },
    // 选择位置回调
    onSelectArea(data) {
      const { termIndex, unitType, list } = this.currTermAreas
      const term = this.inspectionData.terms[termIndex]

      list.map(item => {
        const { stdIndex, areaIndex, area } = item
        // position 赋值到 area
        assignAreaPosition(unitType, area, data.position)
        term.standardList[stdIndex].areaList[areaIndex] = area
      })
      // 处理多层嵌套导致页面数据不同步
      this.$set(this.inspectionData.terms, termIndex, term)
    },
    // 批量设置位置
    btnSelectStandardArea() {
      const { termIndex } = this.currTermAreas
      const standardList = this.inspectionData.terms[termIndex].standardList
      let firstStd = null
      let firstArea = null

      const list = []
      standardList.map((std, stdIndex) => {
        std.areaList.map((area, areaIndex) => {
          if (area.checked) {
            list.push({ stdIndex, areaIndex, area })
            if (firstArea) return
            firstStd = std
            firstArea = area
          }
        })
      })

      this.currTermAreas = { termIndex, unitType: firstStd.unitType, list }
      this.resetAllCheckbox()

      this.$refs.SelectArea.open({
        rdcScore: this.checkRecordRow,
        currArea: firstArea,
        scoreType: 'gldz',
        unitType: firstStd.unitType,
        isFirezone: firstStd.isFirezone
      })
    },
    // 选取位置(用于单个)
    selectStandardArea(point, area, termIndex, stdIndex, areaIndex) {
      if (this.isMultiAreas) return
      if (point.result === -1) return this.$message.info('甩项不能操作')

      const list = [{ stdIndex, areaIndex, area }]
      this.currTermAreas = { termIndex, unitType: point.unitType, list }
      this.resetAllCheckbox()

      this.$refs.SelectArea.open({
        rdcScore: this.checkRecordRow,
        currArea: area,
        scoreType: 'gldz',
        unitType: point.unitType,
        isFirezone: point.isFirezone
      })
    },
    // 打开选择图片文件
    openSelectFileList(termIndex, stdIndex) {
      this.currStandard = { termIndex, stdIndex }
      const opt = {
        processType: this.checkRecordRow.processType,
        taskId: this.checkRecordRow.randomId,
        scoreType: 'gldz'
      }
      this.$refs.SelectFileList.open(opt)
    },
    // 选择图片文件回调
    onSelectFileList(data) {
      const rdcScore = this.checkRecordRow
      const { termIndex, stdIndex } = this.currStandard
      const list = this.inspectionData.terms[termIndex].standardList[stdIndex].areaList

      data.map(item => {
        list.push({
          checked: false,
          projectId: rdcScore.projectId,
          taskFileId: item.taskFileId,
          fileId: item.fileId,
          url: item.url
        })
      })
      this.overallEvaluation()
      this.msgSuccess(`已添加${data.length}个文件`)
    }
  }
}
</script>

<style scoped lang='scss'>
  .calculate-score {
    overflow-y: auto;
    padding-right: 10px;
    .base-terms-content {
      padding-left: 30px;
      .location-type-all {
        display: flex;
        justify-content: flex-end;
        margin: -10px 0 20px;
        position: -webkit-sticky;
        position: sticky;
        top: 0px;
        background-color: #ffffff;
        z-index: 100;
      }
      .base-terms-item {
        .all-no-check {
          flex: 1;
          text-align: right;
          padding-right: 30px;
        }
        .gldz-module {
          background-color: #ebf9d9;
          color: #67C23A;
          font-size: 16px;
          font-weight: bold;
          padding: 14px;
          border-radius: 4px;
          display: flex;
          margin: 6px -20px 20px 0;
        }
        .gldz-module-danger {
          background-color: #fef0f0;
          color: #F56C6C;
        }
        .check-type {
          color: #333;
          font-size: 16px;
          box-sizing: border-box;
          font-weight: 700;
          padding: 10px 0;
          flex-grow: 1;
          .location-type {
            margin-left: 20px;
          }
        }
        .point-content {
          padding: 16px;
          background-color: #f5f9ff;
          border-radius: 5px;
          margin-top: 10px;
          border: 1px #cbdfff solid;
          .point-descr {
            font-size: 14px;
            box-sizing: border-box;
            font-weight: 700;
            margin: 10px 0 20px 0;
            display: flex;
            align-items: center;
            justify-content: space-between;
            .rule-content {
              cursor: pointer;
              font-size: 16px;
              color: #333333;
              margin-left: 10px;
              &:hover {
                color: #409EFF;
              }
            }
            .no-check {
              margin-right: 20px;
            }
          }
          .operater-condition {
            margin-bottom: 16px;
          }
          .data-row {
            position: relative;
            .operater-first {
              display: inline-block;
              width: 300px;
              .input-width {
                width: 230px;
              }
            }
            .remain-desc {
              font-size: 12px;
              color: #ff3e4c;
              margin-top: 6px;
            }
            .violate-standard {
              margin-left: 20px;
            }
          }
          .standard-check-area {
            margin-top: 10px;
          }
          .plan-upload-btn {
            margin-top: 20px;
          }
        }
      }
      .design-label {
        font-weight: 600;
        margin-right: 20px;
      }
      .value-grade {
        margin:6px 0 0 96px;
        color: #898989;
        font-size: 12px;
      }
    }
    .danger {
      color: rgb(255, 62, 76);
    }
  }
  // 图片位置列表
  .vos-area-list {
    display: flex;
    flex-wrap: wrap;
    .item {
      position: relative;
      width: 64px;
      margin: 10px 10px 0 0;
      color: #606266;
      &:hover {
        .btn-del {
          display: block;
        }
        .area-checkbox {
          display: inline-block;
        }
      }
    }
    .btn-del {
      position: absolute;
      top: -5px;
      right: -5px;
      z-index: 1;
      display: none;
      background-color: white;
      border-radius: 50%;
      cursor: pointer;
      &:hover {
        color: #409eff;
      }
    }
    .img {
      width: 64px;
      height: 64px;
      border-radius: 6px;
      cursor: pointer;
    }
    .area-name {
      height: 32px;
      font-size: 12px;
      line-height: 16px;
      &:hover {
        color: #409eff;
      }
    }
    .pointer {
      cursor: pointer;
    }
    .area-checkbox {
      margin-right: 2px;
      display: none;
      &.checked {
        display: inline-block;
      }
    }
    .area-select-img {
      width: 66px;
      height: 66px;
      line-height: 72px;
      text-align: center;
    }
  }
  .calculate-score-collapse {
    /deep/.el-collapse-item__header {
      height: auto;
      line-height: normal;
      i {
        align-self: end;
        margin-bottom: 20px;
      }
    }
  }
</style>
